"""
task取消和子协程调用原理

核心知识点：
    1.loop会被放到future中
"""

import asyncio


async def get_html(sleep_times):
    print("waiting")
    await asyncio.sleep(sleep_times)
    print("done after {} 秒".format(sleep_times))


if __name__ == '__main__':
    task1 = get_html(2)
    task2 = get_html(3)
    task = [task1, task2]

    loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(asyncio.wait(task))
    except KeyboardInterrupt as e:
        all_task = asyncio.Task.all_tasks()
        for task in all_task:
            print("cancel task")
            print(task.cancel())
        loop.stop()
        # 需要再次启动
        loop.run_forever()
    finally:
        loop.close()

    # 输出结果：
    """
    waiting
    waiting
    done after 2 秒
    done after 3 秒
    """
